﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 串口调试工具
{
    public partial class UCSerialPortClass : UserControl
    {
        private SerialPort serialPort=null;

        public UCSerialPortClass()
        {
            InitializeComponent();
        }

        private void UCSerialPortClass_Load(object sender, EventArgs e)
        {
            if (serialPort == null)
            {
                serialPort = new SerialPort();
                propertyGrid_serialport.SelectedObject = serialPort;
                cb_type.SelectedIndex = 0;

                serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler
                    (new SerialDataReceivedEventHandler((object sdr, System.IO.Ports.SerialDataReceivedEventArgs eargs) => {

                        int len = serialPort.BytesToRead;
                        byte[] sbytes = new byte[len];
                        serialPort.Read(sbytes, 0, len);

                        string str1 = "收到：\r\n" + Encoding.UTF8.GetString(sbytes);
                        string str2 = (ByteToHexString(sbytes) + "\r\n");

                        AddChildNode(str1, str2);
                    }));
            }
        }

        private void btn_clear_Click(object sender, EventArgs e)
        {
            this.treeView1.Nodes.Clear();
        }

        private void btn_open_Click(object sender, EventArgs e)
        {
            try
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }

                serialPort.Open();

            }
            catch (Exception ex)
            {
                lbl_tips.ForeColor = Color.Red;
                lbl_tips.Text = "打开串口出错";
                AddRootNode(lbl_tips.Text);
                return;
            }
            lbl_tips.ForeColor = Color.Green;
            lbl_tips.Text = "串口已打开";
            AddRootNode(lbl_tips.Text);
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            if (serialPort.IsOpen)
            {
                serialPort.Close();
                lbl_tips.ForeColor = Color.Green;
                lbl_tips.Text = "关闭串口成功";
                AddRootNode(lbl_tips.Text);
                return;
            }
            lbl_tips.ForeColor = Color.Black;
            lbl_tips.Text = "关闭串口成功";

            AddRootNode(lbl_tips.Text);
        }


        private void btn_send_Click(object sender, EventArgs e)
        {
            string type = cb_type.Text;

            if (type == "字符串")
            {
                string str = txt_content.Text;

                byte[] BSendTemp = System.Text.Encoding.ASCII.GetBytes(str);

                serialPort.Write(BSendTemp, 0, BSendTemp.Length);//发送数据    

                string str1= "发送字符串：\r\n" + str + "\r\n";
                string str2= (ByteToHexString(BSendTemp) + "\r\n"); ;


                AddChildNode(str1, str2);
            }

            if (type == "16进制")
            {
                string hexstr = txt_content.Text;
                Byte[] BSendTemp = HexStringToBytes(hexstr);

                serialPort.Write(BSendTemp, 0, BSendTemp.Length);//发送数据    

                string str1= "发送16进制：\r\n" + hexstr + "\r\n";
                string str2 = (Encoding.UTF8.GetString(BSendTemp) + "\r\n");


                AddChildNode(str1, str2);
            }
            
        }

        public static byte[] HexStringToBytes(string hs)
        {
            string[] strArr = hs.Trim().Split(' ');
            byte[] b = new byte[strArr.Length];
            //逐个字符变为16进制字节数据
            for (int i = 0; i < strArr.Length; i++)
            {
                b[i] = Convert.ToByte(strArr[i], 16);
            }
            //按照指定编码将字节数组变为字符串
            return b;
        }

        public string ByteToHexString(byte[] byteDatas)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < byteDatas.Length; i++)
            {
                builder.Append(string.Format("{0:X2} ", byteDatas[i]));
            }
            return builder.ToString().Trim();
        }

        public void AddRootNode(string str)
        {
            treeView1.BeginInvoke(new MethodInvoker(() => {
                treeView1.Nodes.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + str);
                this.treeView1.Nodes[treeView1.Nodes.Count - 1].EnsureVisible();
            }));
        }

        public void AddChildNode(string str1,string str2)
        {
            treeView1.BeginInvoke(new MethodInvoker(() => {
                TreeNode tn = new TreeNode();
                tn.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + str1;
                tn.Nodes.Add(str2);
                treeView1.Nodes.Add(tn);

                this.treeView1.Nodes[treeView1.Nodes.Count-1].EnsureVisible();
            }));
            
        }


    }
}
